package com.lagou.code.controller;

import com.lagou.code.service.MailFeighClient;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/code")
public class CodeController {

    @Autowired
    public MailFeighClient mailFeighClient;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @GetMapping("/validate/{email}/{code}")
    public Integer validateEmailCode(@PathVariable (value = "email")  String email, @PathVariable(value = "code") String code) {

        System.out.println("====>>>>>>>>>>>>>>CodeController sendEmailCode，访问到我这里了......"+email);

        String s = redisTemplate.opsForValue().get(email);
        System.out.println("validateEmailCode    "+s);
        if(StringUtils.isEmpty(s)){
            return 2;
        }else{
            if(s.equals(code)){
                return 0;
            }else {
                return 1;
            }
        }

    }

    @GetMapping("/create/{email}")
    public Integer sendEmailCode(@PathVariable String email ) {

        System.out.println("====>>>>>>>>>>>>>>我是code，访问到我这里了......"+email);

        String mailCode = RandomStringUtils.randomNumeric(6);

        //放入缓存
        redisTemplate.opsForValue().set(email,mailCode,15, TimeUnit.MINUTES);

        mailFeighClient.sendEmail(email,mailCode);

        return 1122;
    }
}
